<?php
$url=$_GET['url'];
if($url==''){
	echo "<script>alert('请输入视频地址后再试')</script>";
}elseif ($url != '') {
	// 获取vde
	$vde = init_video($url);
	$url = "http://api.cntv.cn/NewVideoset/getVideoAlbumInfoByVideoId?serviceId=tvcctv&id=".$vde;
	$subStrings = request($url);
	// 获取视频播放id
	$vda = getVDAInfo($subStrings);
	// print("====VDA:".$vda."=====VDE:".$vde);
	$lastUrl = "http://api.cntv.cn/video/getVideoListByAlbumIdInfo?videoid=".$vde."&videoalbumid=".$vda."&serviceId=tvcctv";
	$vadInfo = request($lastUrl);
	// print($vadInfo);
	$result = json_decode($vadInfo);
	$guid = "";
	$data = $result -> data;
	foreach ($data as $item) {
		$data_vde = $item -> video_id;
		if($data_vde == $vde){
			$guid = $item -> guid;
		}
}
	// var_dump($guid);
	result_url($guid);
}


// 初始化视频参数
function init_video($url){
	preg_match('/V.*.sh/', $url, $matches);
	$feat = $matches[0];
	$vde = str_replace('.sh','',$feat);
	return $vde;
}
// 发送请求，返回内容
function request($url,$https=true,$method='GET',$data=null) {
	$ch = curl_init();
	//初始化，得到资源
	curl_setopt($ch, CURLOPT_URL,$url);
	//请求数据的路径
	curl_setopt($ch, CURLOPT_HEADER,false);
	//是否输出头
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	//不直接输出结果
	//curl_setopt ($ch, CURLOPT_SAFE_UPLOAD, 0);
	//兼容php之后的版本
	if($https) {
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
		//是否验证主机
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
		//是否进行证书验证
	}
	if($method=='POST') {
		curl_setopt($ch, CURLOPT_POST, true);
		//POST传输
		curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
		//传输数据
	}
	$content_json = curl_exec($ch);
	if ($content_json === false) {
		return "网络请求出错: " . curl_error($ch);
	}
	curl_close($ch);
	return $content_json;
}

// 获取请求后的结果
function result_url($str){
	$resultUrl = "https://hls.cntv.myhwcdn.cn/asp/hls/main/0303000a/3/default/".$str."/main.m3u8?maxbr=2048";
	var_dump($resultUrl);
	header('location:'.urldecode($resultUrl));
}

// 获取VDA信息
function getVDAInfo($content_json){
	$result = json_decode($content_json);
	$vda = $result -> data -> id;
	return $vda;
}